<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的评价</title>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }
        .header {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
            padding: 20px 0;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
        }
        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header-title {
            font-size: 24px;
            font-weight: 600;
            color: #333;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .header-title::before {
            content: "📝";
            font-size: 28px;
        }
        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
            background: rgba(255, 255, 255, 0.8);
            padding: 10px 20px;
            border-radius: 25px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .user-avatar {
            width: 40px;
            height: 40px;
            background: linear-gradient(45deg, #667eea, #764ba2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 18px;
        }
        .user-name {
            font-weight: 500;
            color: #333;
        }
        .user-action-btn {
            background: #f5f5f5;
            border: none;
            color: #5a3ec8;
            padding: 6px 16px;
            border-radius: 16px;
            margin-left: 8px;
            font-size: 14px;
            cursor: pointer;
            transition: background 0.2s, color 0.2s;
            text-decoration: none;
            display: inline-block;
        }
        .user-action-btn:hover {
            background: #e0e7ff;
            color: #333;
        }
        .main-content {
            max-width: 900px;
            margin: 120px auto 40px;
            padding: 0 20px;
        }
        .reviews-title {
            font-size: 28px;
            font-weight: 600;
            color: #333;
            margin-bottom: 30px;
            text-align: center;
        }
        .reviews-list {
            display: flex;
            flex-direction: column;
            gap: 24px;
        }
        .review-card {
            background: rgba(255,255,255,0.95);
            border-radius: 16px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
            padding: 24px 32px;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        .review-card .review-header {
            font-size: 18px;
            font-weight: 500;
            color: #5a3ec8;
        }
        .review-card .review-info {
            font-size: 15px;
            color: #555;
        }
        .review-card .review-rating {
            font-size: 16px;
            color: #ffd700;
            margin-top: 6px;
            display: flex;
            gap: 2px;
        }
        .review-card .review-rating .star-filled {
            color: #ffd700;
            text-shadow: 0 0 5px rgba(255, 0, 0.3);
        }
        .review-card .review-text {
            font-size: 15px;
            color: #333;
            margin-top: 6px;
        }
        .review-actions {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        .append-btn {
            background: #5a3ec8;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 12px;
            font-size: 12px;
            cursor: pointer;
            transition: background 0.2s;
        }
        .append-btn:hover {
            background: #764ba2;
        }
        .edit-btn {
            background: #28a745;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 12px;
            font-size: 12px;
            cursor: pointer;
            transition: background 0.2s;
        }
        .edit-btn:hover {
            background: #218838;
        }
        .append-modal, .edit-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1001;
        }
        .append-content, .edit-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 30px;
            border-radius: 16px;
            width: 400px;
            max-width: 90%;
        }
        .append-title, .edit-title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 20px;
            text-align: center;
        }
        .append-text, .edit-text {
            width: 100%;
            height: 100px;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 10px;
            resize: vertical;
            margin-bottom: 20px;
        }
        .append-actions, .edit-actions {
            display: flex;
            justify-content: space-between;
            gap: 10px;
        }
        .append-actions button, .edit-actions button {
            padding: 6px 16px;
            border-radius: 8px;
            border: none;
            font-size: 14px;
            cursor: pointer;
        }
        .append-actions .cancel-btn, .edit-actions .cancel-btn {
            background: #eee;
            color: #333;
        }
        .append-actions .submit-btn, .edit-actions .submit-btn {
            background: #5a3ec8;
            color: white;
        }
        .append-actions .submit-btn:hover, .edit-actions .submit-btn:hover {
            background: #764ba2;
        }
        .edit-star-rating {
            display: flex;
            justify-content: center;
            gap: 8px;
            margin-bottom: 20px;
        }
        .edit-star {
            font-size: 28px;
            cursor: pointer;
            color: #ddd;
            transition: all 0.3s ease;
            position: relative;
            user-select: none;
        }
        .edit-star:hover {
            color: #ffd700;
            transform: scale(1.1);
        }
        .edit-star.active {
            color: #ffd700;
            text-shadow: 0 0 10px rgba(255, 0, 0.5);
        }
        .edit-actions .delete-btn {
            background: #dc3545;
            color: white;
        }
        .edit-actions .delete-btn:hover {
            background: #c82333;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-content">
            <div class="header-title">我的评价</div>
            <div class="user-info">
                <div class="user-avatar" id="userAvatar"></div>
                <div class="user-name" id="userName"></div>
                <a href="myorders.html" class="user-action-btn">我的订单</a>
                <a href="index.html" class="user-action-btn">返回首页</a>
                <button class="user-action-btn" id="logoutBtn">退出登录</button>
            </div>
        </div>
    </div>
    <div class="main-content">
        <div class="reviews-title">我的评价记录</div>
        <div class="reviews-list" id="reviewsList"></div>
    </div>
    <!-- 追评弹窗 -->
    <div class="append-modal" id="appendModal">
        <div class="append-content">
            <div class="append-title">追加评价</div>
            <textarea class="append-text" id="appendText" placeholder="请输入追加评价内容..."></textarea>
            <div class="append-actions">
                <button class="cancel-btn" id="cancelAppend">取消</button>
                <button class="submit-btn" id="submitAppend">提交</button>
            </div>
        </div>
    </div>
    <!-- 编辑弹窗 -->
    <div class="edit-modal" id="editModal">
        <div class="edit-content">
            <div class="edit-title">编辑评价</div>
            <div class="edit-star-rating">
                <span class="edit-star" data-rating="1">★</span>
                <span class="edit-star" data-rating="2">★</span>
                <span class="edit-star" data-rating="3">★</span>
                <span class="edit-star" data-rating="4">★</span>
                <span class="edit-star" data-rating="5">★</span>
            </div>
            <textarea class="edit-text" id="editText" placeholder="请输入评价内容..."></textarea>
            <div class="edit-actions">
                <button class="cancel-btn" id="cancelEdit">取消</button>
                <button class="delete-btn" id="deleteReview">删除</button>
                <button class="submit-btn" id="submitEdit">提交</button>
            </div>
        </div>
    </div>
    <script>
        // 用户信息展示
        $(function() {
            // 兼容两种存储方式
            var user = null;
            var userStr = sessionStorage.getItem('user');
            if (userStr) {
                try {
                    user = JSON.parse(userStr);
                } catch(e) {
                    user = null;
                }
            }
            
            // 如果没有 user 对象，尝试从旧的存储方式获取
            if (!user) {
                var userId = sessionStorage.getItem('userId');
                var username = sessionStorage.getItem('adminName');
                if (userId && username) {
                    user = {
                        userId: parseInt(userId),
                        username: username
                    };
                }
            }
            
            if (!user) {
                window.location.href = 'login.html';
                return;
            }
            
            $('#userAvatar').text(user.username.charAt(0).toUpperCase());
            $('#userName').text(user.username);
            $('#logoutBtn').click(function() {
                sessionStorage.removeItem('user');
                sessionStorage.removeItem('userId');
                sessionStorage.removeItem('adminName');
                window.location.href = 'login.html';
            });

            // 加载评价列表
            loadReviews(user.userId);
        });

        let reviews = [];
        let appendOrderId = null;
        let currentEditReviewId = null;
        let currentEditRating = 0;
        let currentEditText = '';
        var isEditRatingLocked = false;

        function loadReviews(userId) {
            $.get('http://localhost:8080/api/order/reviews', { userId: userId }, function(data) {
                reviews = data;
                renderReviews();
            });
        }

        // 追加评价弹窗逻辑
        window.showAppendModal = function(orderId) {
            appendOrderId = orderId;
            $('#appendText').val('');
            $('#appendModal').show();
        };
        $('#cancelAppend').click(function() {
            $('#appendModal').hide();
        });
        $('#submitAppend').click(function() {
            let content = $('#appendText').val().trim();
            if (!content) {
                alert('请输入追加评价内容');
                return;
            }
            // 新增：调用追评表接口
            var user = null;
            var userStr = sessionStorage.getItem('user');
            if (userStr) {
                try { user = JSON.parse(userStr); } catch(e) { user = null; }
            }
            if (!user) {
                var userId = sessionStorage.getItem('userId');
                var username = sessionStorage.getItem('adminName');
                if (userId && username) {
                    user = { userId: parseInt(userId), username: username };
                }
            }
            $.ajax({
                url: 'http://localhost:8080/api/order/appendReview/add',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ orderId: appendOrderId, userId: user.userId, username: user.username, appendText: content }),
                success: function(res) {
                    if (res === 'success') {
                        $('#appendModal').hide();
                        loadReviews(user.userId);
                    } else {
                        alert('追加评价失败');
                    }
                }
            });
        });

        // 编辑评价弹窗逻辑
        window.showEditModal = function(reviewId) {
            currentEditReviewId = reviewId;
            const review = reviews.find(r => r.reviewId === reviewId);
            if (review) {
                currentEditRating = review.rating;
                currentEditText = review.reviewText;
                renderEditStars();
                $('#editText').val(currentEditText);
                $('#editModal').show();
            }
        }

        function renderEditStars() {
            $('.edit-star').removeClass('active');
            for (let i = 0; i < 5; i++) {
                if (i < currentEditRating) {
                    $(`.edit-star[data-rating="${i + 1}"]`).addClass('active');
                }
            }
        }

        $('#cancelEdit').click(function() {
            $('#editModal').hide();
        });

        $('#submitEdit').click(function() {
            let rating = currentEditRating;
            let content = $('#editText').val().trim();

            if (!content) {
                alert('评价内容不能为空');
                return;
            }

            $.ajax({
                url: 'http://localhost:8080/api/order/review/update',
                method: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify({
                    reviewId: currentEditReviewId,
                    rating: rating,
                    content: content
                }),
                success: function(res) {
                    if (res === 'success') {
                        $('#editModal').hide();
                        // 重新加载评价
                        var user = JSON.parse(sessionStorage.getItem('user'));
                        if (!user) {
                            var userId = sessionStorage.getItem('userId');
                            var username = sessionStorage.getItem('adminName');
                            if (userId && username) {
                                user = {
                                    userId: parseInt(userId),
                                    username: username
                                };
                            }
                        }
                        loadReviews(user.userId);
                    } else {
                        alert('更新评价失败');
                    }
                },
                error: function(xhr, status, error) {
                    alert('更新评价失败: ' + error);
                }
            });
        });

        // 删除评价逻辑
        $('#deleteReview').click(function() {
            // 判断是主体评价还是追评
            const review = reviews.find(r => r.reviewId === currentEditReviewId);
            let deleteType = 'single'; // 默认删除单条
            let confirmMessage = '确定要删除这条追评吗？';
            
            if (review && review.rating > 0) {
                // 如果是主体评价（有评分），删除该订单的所有评价
                deleteType = 'all';
                confirmMessage = '确定要删除这条主体评价吗？删除后将同时删除该订单的所有追评！';
            }
            
            if (confirm(confirmMessage)) {
                $.ajax({
                    url: 'http://localhost:8080/api/order/review/delete?reviewId=' + currentEditReviewId + '&deleteType=' + deleteType,
                    method: 'POST',
                    success: function(res) {
                        if (res === 'success') {
                            $('#editModal').hide();
                            // 重新加载评价
                            var user = JSON.parse(sessionStorage.getItem('user'));
                            if (!user) {
                                var userId = sessionStorage.getItem('userId');
                                var username = sessionStorage.getItem('adminName');
                                if (userId && username) {
                                    user = {
                                        userId: parseInt(userId),
                                        username: username
                                    };
                                }
                            }
                            loadReviews(user.userId);
                        } else {
                            alert('删除评价失败');
                        }
                    },
                    error: function(xhr, status, error) {
                        alert('删除评价失败: ' + error);
                    }
                });
            }
        });

        // 星级点击事件
        $(document).on('click', '.edit-star', function() {
            let rating = parseInt($(this).data('rating'));
            if (!isEditRatingLocked) {
                currentEditRating = rating;
                isEditRatingLocked = true;
                renderEditStars();
            } else {
                // 已锁定，再次点击任意星星解锁
                isEditRatingLocked = false;
                currentEditRating = 0;
                renderEditStars();
            }
        });
        
        // 星星悬停预览效果
        $(document).on('mouseenter', '.edit-star', function() {
            if (isEditRatingLocked) return;
            let rating = parseInt($(this).data('rating'));
            $('.edit-star').removeClass('active');
            for (let i = 0; i < rating; i++) {
                $(`.edit-star[data-rating="${i + 1}"]`).addClass('active');
            }
        });
        
        $(document).on('mouseleave', '.edit-star-rating', function() {
            if (isEditRatingLocked) return;
            renderEditStars();
        });

        // 渲染时嵌套追评，添加编辑按钮
        function renderReviews() {
            let html = '';
            let orderMap = {};
            reviews.forEach(function(r) {
                if (!orderMap[r.orderId]) orderMap[r.orderId] = [];
                orderMap[r.orderId].push(r);
            });
            for (let orderId in orderMap) {
                let group = orderMap[orderId];
                let mainReview = group.find(r => r.rating > 0);
                if (mainReview) {
                    var filledStars = Array(mainReview.rating).fill('<span class="star-filled">★</span>').join('');
                    html += `<div class="review-card">
                        <div class="review-header">订单号：${mainReview.orderId}</div>
                        <div class="review-info">用户名：${mainReview.username}</div>
                        <div class="review-rating">评分：${filledStars}</div>
                        <div class="review-text">${mainReview.reviewText}</div>
                        <div class="review-actions">
                            <button class="edit-btn" onclick="showEditModal(${mainReview.reviewId})">编辑评价</button>
                            <button class="append-btn" onclick="showAppendModal('${mainReview.orderId}')">追加评价</button>
                        </div>
                        <div class="review-appends" id="appends_${mainReview.orderId}"></div>
                    </div>`;
                }
            }
            if (!html) html = '<div style="text-align:center;color:#888;">暂无评价记录</div>';
            $('#reviewsList').html(html);
            // 逐条查追评
            for (let orderId in orderMap) {
                $.get('http://localhost:8080/api/order/appendReview/list', {orderId: orderId}, function(appends) {
                    if(appends && appends.length > 0) {
                        let appendHtml = '<div class="append-title">追评：</div>';
                        appends.forEach(function(a) {
                            appendHtml += `<div class="append-item">${a.appendText} <span class="append-time">${a.appendTime ? a.appendTime.replace('T',' ').substring(0,16) : ''}</span> <button class='edit-append-btn' data-appendid='${a.appendId}' data-appendtext='${a.appendText.replace(/'/g, '&#39;')}'>编辑</button></div>`;
                        });
                        $('#appends_' + orderId).html(appendHtml);
                    }
                });
            }
        }

        // 追加样式
        $('<style>.review-appends{margin-top:10px;}.append-title{color:#5a3ec8;font-weight:bold;margin-bottom:4px;}.append-item{background:#f7f3ff;border-radius:8px;padding:6px 10px;margin-bottom:4px;font-size:14px;display:flex;align-items:center;}.append-time{color:#aaa;font-size:12px;margin-left:8px;}.edit-append-btn{margin-left:10px;padding:2px 10px;border-radius:6px;border:none;background:#e0e7ff;color:#5a3ec8;cursor:pointer;transition:background 0.2s;}.edit-append-btn:hover{background:#d1c4e9;}</style>').appendTo('head');
        // 追评编辑弹窗
        $('body').append(`<div class="edit-append-modal" id="editAppendModal" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:2000;"><div class="edit-append-content" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);background:white;padding:30px;border-radius:16px;width:400px;max-width:90%;"><div class="edit-append-title" style="font-size:20px;font-weight:bold;margin-bottom:20px;text-align:center;">编辑追评</div><textarea class="edit-append-text" id="editAppendText" style="width:100%;height:100px;border:1px solid #ddd;border-radius:8px;padding:10px;resize:vertical;margin-bottom:20px;"></textarea><div class="edit-append-actions" style="display:flex;justify-content:space-between;gap:10px;"><button class="cancel-btn" id="cancelEditAppend">取消</button><button class="delete-btn" id="deleteEditAppend">删除</button><button class="submit-btn" id="submitEditAppend">提交</button></div></div></div>`);
        let currentEditAppendId = null;
        $(document).on('click','.edit-append-btn',function(){
            currentEditAppendId = $(this).data('appendid');
            $('#editAppendText').val($(this).data('appendtext'));
            $('#editAppendModal').show();
        });
        $('#cancelEditAppend').click(function(){ $('#editAppendModal').hide(); });
        $('#submitEditAppend').click(function(){
            let newText = $('#editAppendText').val().trim();
            if(!newText){ alert('追评内容不能为空'); return; }
            $.ajax({
                url:'http://localhost:8080/api/order/appendReview/update',
                type:'PUT',
                contentType:'application/json',
                data:JSON.stringify({appendId:currentEditAppendId,appendText:newText}),
                success:function(res){
                    if(res==='success'){
                        $('#editAppendModal').hide();
                        // 重新加载评价
                        var user = null;
                        var userStr = sessionStorage.getItem('user');
                        if (userStr) { try { user = JSON.parse(userStr); } catch(e) { user = null; } }
                        if (!user) {
                            var userId = sessionStorage.getItem('userId');
                            var username = sessionStorage.getItem('adminName');
                            if (userId && username) { user = { userId: parseInt(userId), username: username }; }
                        }
                        loadReviews(user.userId);
                    }else{
                        alert('追评更新失败');
                    }
                }
            });
        });
        $('#deleteEditAppend').off('click').on('click', function(){
            if(!currentEditAppendId) return;
            if(!confirm('确定要删除这条追评吗？')) return;
            $.ajax({
                url:'http://localhost:8080/api/order/appendReview/delete',
                type:'POST',
                data: $.param({appendId: currentEditAppendId}),
                contentType: 'application/x-www-form-urlencoded',
                success:function(res){
                    if(res==='success'){
                        $('#editAppendModal').hide();
                        // 重新加载评价
                        var user = null;
                        var userStr = sessionStorage.getItem('user');
                        if (userStr) { try { user = JSON.parse(userStr); } catch(e) { user = null; } }
                        if (!user) {
                            var userId = sessionStorage.getItem('userId');
                            var username = sessionStorage.getItem('adminName');
                            if (userId && username) { user = { userId: parseInt(userId), username: username }; }
                        }
                        loadReviews(user.userId);
                    }else{
                        alert('追评删除失败');
                    }
                }
            });
        });
        // 追加样式
        $('<style>.delete-btn{background:#dc3545;color:white;}.delete-btn:hover{background:#c82333;}</style>').appendTo('head');
    </script>
    <script>
        // 美化追评编辑弹窗
        $('#editAppendModal .edit-append-content').css({
            'background': '#fff',
            'border-radius': '20px',
            'box-shadow': '0 8px 32px rgba(90,62,200,0.18)',
            'padding': '36px 32px 28px 32px',
            'width': '420px',
            'max-width': '96vw',
            'min-width': '260px',
            'font-family': "'Segoe UI', 'Microsoft YaHei', Arial, sans-serif"
        });
        $('#editAppendModal .edit-append-title').css({
            'font-size': '22px',
            'font-weight': '800',
            'color': '#5a3ec8',
            'margin-bottom': '18px',
            'letter-spacing': '1px',
            'text-align': 'center'
        });
        $('#editAppendText').css({
            'border-radius': '10px',
            'border': '1.5px solid #b3a6e6',
            'background': 'linear-gradient(90deg, #f5f5ff 0%, #e0e7ff 100%)',
            'color': '#333',
            'font-size': '15px',
            'font-family': "'Segoe UI', 'Microsoft YaHei', Arial, sans-serif"
        });
        $('#editAppendModal .edit-append-actions').css({
            'display': 'flex',
            'justify-content': 'space-between',
            'gap': '12px',
            'margin-top': '10px'
        });
        $('#editAppendModal .cancel-btn').css({
            'background': '#f5f5f5',
            'color': '#5a3ec8',
            'border': 'none',
            'border-radius': '10px',
            'padding': '8px 24px',
            'font-size': '15px',
            'font-weight': '500',
            'cursor': 'pointer',
            'transition': 'background 0.2s, color 0.2s',
            'box-shadow': '0 2px 8px #e0d7f7'
        });
        $('#editAppendModal .cancel-btn').hover(function(){$(this).css({'background':'#e0e7ff','color':'#333'});},function(){$(this).css({'background':'#f5f5f5','color':'#5a3ec8'});});
        $('#editAppendModal .submit-btn').css({
            'background': 'linear-gradient(90deg, #764ba2 0%, #667eea 100%)',
            'color': '#fff',
            'border': 'none',
            'border-radius': '10px',
            'padding': '8px 24px',
            'font-size': '15px',
            'font-weight': '600',
            'cursor': 'pointer',
            'transition': 'background 0.2s, color 0.2s',
            'box-shadow': '0 2px 8px #e0d7f7'
        });
        $('#editAppendModal .submit-btn').hover(function(){$(this).css({'background':'linear-gradient(90deg, #a18cd1 0%, #fbc2eb 100%)','color':'#5a3ec8'});},function(){$(this).css({'background':'linear-gradient(90deg, #764ba2 0%, #667eea 100%)','color':'#fff'});});
        $('#editAppendModal .delete-btn').css({
            'background': '#dc3545',
            'color': 'white',
            'border': 'none',
            'border-radius': '10px',
            'padding': '8px 24px',
            'font-size': '15px',
            'font-weight': '600',
            'cursor': 'pointer',
            'transition': 'background 0.2s',
            'box-shadow': '0 2px 8px #e0d7f7'
        });
        $('#editAppendModal .delete-btn').hover(function(){$(this).css({'background':'#c82333'});},function(){$(this).css({'background':'#dc3545'});});
    </script>
</body>
</html> 